<?php


namespace app\job;
use app\service\propertyService;
use app\service\RedisQueueService;
use app\service\zftService;
use app\zftpay\service\apiService;
use think\facade\Db;
use think\queue\Job;
use think\queue\ShouldQueue;

//账单结算
class ZftSettleQueryOrder implements ShouldQueue
{
    public $jobData;

    public function __construct($jobData)
    {
        $this->jobData = $jobData;
    }

    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job,$data){
        // 如有必要,可以根据业务需求和数据库中的最新数据,判断该任务是否仍有必要执行.
        //执行收单交易结算

        $isJobDone = $this->doJob($this->jobData);
        print("<info>ZftSettleOrderQuery Job Started. job Data is: ".var_export($isJobDone,true)."</info> \n");

        if ($isJobDone) {
            $job->delete();
        }else{
            if ($job->attempts() > 3) {
                //记录开票推送失败的记录
                $job->delete();

                (new RedisQueueService())->push("ZftSettleOrderQueryFailed",$data["id"]);

            }
        }
    }

    public function doJob($data){
        $info=Db::table("zft_settle_order")->where("id",$data["id"])->find();
        if(!empty($info)){
            $query["settle_no"]=$info["settle_no"];//$info["settle_no"];
            $api=new zftService();
            $result = $api->settleQuery(json_encode($query));


            $add_log["result_code"]=$result->code;
            $add_log["settle_order_id"]=$info["id"];
            $add_log["settle_no"]=$info["settle_no"];
            $add_log["create_time"]=date("Y-m-d H:i:s");
            if($result->code==10000){
                $add_log["result_msg"]=$result->msg;
                $add_log["out_request_no"]=$result->out_request_no;
                $add_log["operation_dt"]=$result->operation_dt;
                $add_log["royalty_detail_list"]=json_encode($result->royalty_detail_list);
                Db::table("zft_settle_order")->where("id",$info["id"])->update(["status"=>1]);
                Db::table("zft_order_success")->where("uid",$info["order_uid"])->update(["settle_status"=>1]);
                Db::table("zft_log_settle_order_query")->insert($add_log);
            }else{
                $add_log["result_msg"]=$result->msg;
                $add_log["sub_code"]=$result->sub_code;

                Db::table("zft_log_settle_order_query")->insert($add_log);
            }
        }
        return true;
    }
}